package com.ihrm.common.controller;

import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;

    protected String companyId;
    protected String companyName;
    protected Claims claims;

    @Autowired
    protected JwtUtils jwtUtils;

    @ModelAttribute
    public void setResAnReq(HttpServletRequest request,HttpServletResponse response) {
        this.request = request;
        this.response = response;

//        方式1
//        String authorization = request.getHeader("Authorization");
//        if(!StringUtils.isEmpty(authorization)){
//            //前后端约定头信息内容以 Bearer+空格+token 形式组成
//            String token = authorization.replace("Bearer ", "");
//            this.claims = jwtUtils.parseJwt(token);
//            this.companyId = (String)claims.get("companyId");
//            this.companyName = (String)claims.get("companyName");
//        }

//        方式2：使用拦截器
        Object userClaims = request.getAttribute("user_claims");
        if(userClaims != null) {
            this.claims = (Claims) userClaims;
            this.companyId = (String)claims.get("companyId");
            this.companyName = (String)claims.get("companyName");
        }
    }
}
